using System;
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Video;

namespace Voodoo.Sauce.Internal.CrossPromo.Canvas
{
	internal class SquareFormat : AFormatManager
	{
		private VideoManager _videoManager;

		private int _retries;

		private void Awake()
		{
			AFormatManager.Instance = this;
			_retries = 1;
			base.gameObject.name = "CrossPromoGameObject";
			CrossPromoEvents.ShowEvent += ((AFormatManager)this).Display;
			CrossPromoEvents.HideEvent += ((AFormatManager)this).Hide;
		}

		private void OnDestroy()
		{
			CrossPromoEvents.ShowEvent -= ((AFormatManager)this).Display;
			CrossPromoEvents.HideEvent -= ((AFormatManager)this).Hide;
		}

		private void Start()
		{
			try
			{
				_videoManager = new VideoManager(GetComponentInChildren<VideoPlayer>(), GetComponentInChildren<RawImage>());
				_videoManager.VideoPlayer.loopPointReached += delegate
				{
					_videoManager.Content.enabled = false;
					Display();
				};
				_videoManager.VideoPlayer.prepareCompleted += delegate
				{
					_videoManager.Content.enabled = true;
					VoodooCrossPromo.Callback.ShownEvent(Asset);
				};
			}
			catch (Exception ex)
			{
				VoodooLog.LogE(VoodooCrossPromo.TAG, ex.ToString());
			}
		}

		public override void Display()
		{
			Asset = null;
			IsActive = true;
			if (!IsWaiting)
			{
				StartCoroutine(StartDisplay());
			}
		}

		private IEnumerator StartDisplay()
		{
			IsWaiting = true;
			yield return new WaitForEndOfFrame();
			yield return WaitCrossPromoReady(_videoManager);
			IsWaiting = false;
			if (!IsActive || Asset == null)
			{
				if (!IsActive)
				{
					Hide();
				}
				else
				{
					_videoManager.StopVideo();
				}
				StartCoroutine(Retry());
			}
			else
			{
				_retries = 1;
				try
				{
					_videoManager.PrepareVideo(Asset);
				}
				catch (Exception message)
				{
					VoodooCrossPromo.Callback.ErrorEvent(message);
				}
			}
		}

		private void OnDisable()
		{
			IsWaiting = false;
			Hide();
		}

		private void OnEnable()
		{
			IsWaiting = false;
		}

		public override void Hide()
		{
			IsActive = false;
			IsWaiting = false;
			_retries = 1;
			if (_videoManager != null)
			{
				_videoManager.StopVideo();
			}
		}

		private IEnumerator Retry()
		{
			if (_retries <= 10)
			{
				int waitInSeconds = (int)Math.Pow(2.0, _retries);
				_retries++;
				yield return new WaitForSeconds(waitInSeconds);
				while (!IsActive)
				{
					yield return null;
				}
				Display();
			}
		}
	}
}
